package com.lswms.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.lswms.common.constant.Constant;
import com.lswms.common.exception.ErrorCode;
import com.lswms.common.exception.RenException;
import com.lswms.common.page.PageInfo;
import com.lswms.common.page.PageRequest;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.common.utils.*;
import com.lswms.dao.YnUserDao;
import com.lswms.dto.YnDcLoginDTO;
import com.lswms.dto.YnUserDTO;
import com.lswms.dto.vo.req.LoginReq;
import com.lswms.dto.vo.req.UpdateUserInfoReq;
import com.lswms.dto.vo.resp.LoginResp;
import com.lswms.entity.YnDcLoginEntity;
import com.lswms.entity.YnSignEntity;
import com.lswms.entity.YnUserEntity;
import com.lswms.redis.SysParamsRedis;
import com.lswms.service.YnDcLoginService;
import com.lswms.service.YnUserService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 用户表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2020-04-25
 */
@Service
@Slf4j
public class YnUserServiceImpl extends CrudServiceImpl<YnUserDao, YnUserEntity, YnUserDTO> implements YnUserService {
   
	@Autowired
    private SysParamsRedis sysParamsRedis;
	
	@Autowired
	YnUserService YnUserService;
	
	@Autowired
	YnDcLoginService ynDcLoginService;

    //图片存放位置
    @Value("${file.img.ddpath}")
    private String imgSavePath;
    
    //图片访问地址
    @Value("${file.img.urlpath}")
    private String urlpath;
    
    //h5访问地址
    @Value("${file.img.h5}")
    private String h5;
    
    @Value("${spring.profiles.active}")
    private String profile;

    @Override
    public QueryWrapper<YnUserEntity> getWrapper(Map<String, Object> params){
    	Long id = (Long)params.get("id");
    	String mobile = (String)params.get("mobile");

        QueryWrapper<YnUserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(id != null, "id", id);
        wrapper.eq(StringUtils.isNotBlank(mobile), "mobile", mobile);
        

        return wrapper;
    }

    /**
     * 登录注册
     */
	@Override
	public LoginResp login(LoginReq dto,HttpServletRequest request) {
		log.info("登录注册，参数:{}",JSON.toJSONString(dto));
		//验证Facebook用户登录信息
		//if(StringUtils.equalsIgnoreCase(profile, "prod")) {
			try{
	            JSONObject retJson = HttpClientUtils.httpGet("https://graph.facebook.com/debug_token?input_token="+dto.getToken()+"&access_token="+URLEncoder.encode("1453315224847733|0bd8356c24e5438929fcf00aa29d5155","UTF-8"));
				//HttpClientUtil httpClientUtil = new HttpClientUtil();
	            //Map<String,String> createMap = new HashMap<String,String>();
				//String httpOrgCreateTestRtn = httpClientUtil.doPost("https://graph.facebook.com/debug_token?input_token="+dto.getToken()+"&access_token=1453315224847733%7C0bd8356c24e5438929fcf00aa29d5155",createMap,"utf-8");
				//JSONObject retJson = JSONObject.parseObject(httpOrgCreateTestRtn);
				log.info("验证Facebook用户登录信息结果：{}",JSON.toJSONString(retJson));
	            //log.info("验证Facebook用户登录信息结果：{}",JSON.toJSONString(httpOrgCreateTestRtn));
	            Object resp = retJson.get("error");
	            if(resp != null){
	            	throw new RenException(ErrorCode.LOGIN_ERROR);
	            }
	        	JSONObject retJson1 = (JSONObject)retJson.get("data");
	            if(retJson1 == null){
	            	throw new RenException(ErrorCode.LOGIN_ERROR);
	            }

	        	Boolean is_valid = retJson1.getBoolean("is_valid");
	        	String app_id = retJson1.getString("app_id");
	        	String user_id = retJson1.getString("user_id");
	        	if(!is_valid || !user_id.equals(dto.getUserId()) || !app_id.equals("1453315224847733")){
	        		throw new RenException(ErrorCode.LOGIN_ERROR);
	        	}
			}catch(Exception e){
				log.error("验证Facebook用户登录信息，异常:{}",e);
			}
		//}
		
		//判断用户是否注册
		QueryWrapper<YnUserEntity> wrapper = new QueryWrapper<>();
		wrapper.eq(StringUtils.isNotBlank(dto.getUserId()), "facebook_id", dto.getUserId());
        //wrapper.like(StringUtils.isNotBlank(username), "username", username);
        //wrapper.orderByDesc("create_date");
		YnUserEntity ynuser = baseDao.selectOne(wrapper);
		//用户id
		if(ynuser == null){
			YnUserEntity user = new YnUserEntity();
			user.setIp(IpUtils.getIpAddr(request));
			user.setFacebookId(dto.getUserId());
			user.setLasttime(ZqDateUtil.yyyyMMddHHmmss(ZqDateUtil.getNow()));
			user.setBalance(BigDecimal.ZERO);
			user.setChallenge(0);
			user.setStatus(1);
			user.setResource(Integer.parseInt(dto.getResource()));
			user.setCreateDate(ZqDateUtil.getNow());
			baseDao.insert(user);
			ynuser = user;
		}else{
			//修改登录信息
			YnUserEntity user = new YnUserEntity();
			user.setIp(IpUtils.getIpAddr(request));
			user.setLasttime(ZqDateUtil.yyyyMMddHHmmss(ZqDateUtil.getNow()));
			user.setId(ynuser.getId());
			user.setUpdateDate(ZqDateUtil.getNow());
			baseDao.updateById(user);
		}
		//token 
		String token = UUID.randomUUID().toString().replaceAll("-", "");
		//保存用户id和token
		sysParamsRedis.set("userinfo:"+ynuser.getId(), token);
		
		LoginResp resp = new LoginResp();
		resp.setToken(token);
		resp.setUserId(ynuser.getId()+"");
		return resp;
	}

	/**
	 * 获取用户信息
	 */
	@Override
	public YnUserDTO userInfo(String userId) {
		log.info("获取用户信息userId:{}",userId);
		QueryWrapper<YnUserEntity> wrapper = new QueryWrapper<>();
		wrapper.eq(StringUtils.isNotBlank(userId), "id", userId);
		YnUserEntity ynuser = baseDao.selectOne(wrapper);
		YnUserDTO user = ConvertUtils.sourceToTarget(ynuser, YnUserDTO.class);
		if(user.getBalance().compareTo(BigDecimal.ZERO) <= 0){
			user.setBalance(BigDecimal.ZERO);
			user.setBalanceStr("0");
		}
		if(user.getReward().compareTo(BigDecimal.ZERO) <= 0){
			user.setReward(BigDecimal.ZERO);
		}

		log.info("获取用户信息返回user:{}",JSON.toJSONString(user));
		return user;
	}

	/**
	 * 修改用户信息
	 */
	@Override
	public void updateUserInfo(UpdateUserInfoReq dto, HttpServletRequest request,YnUserEntity ynuser) {
		
		log.info("修改用户信息，dto:{},ynuser:{}",JSON.toJSONString(dto),JSON.toJSONString(ynuser));
		YnUserEntity user = new YnUserEntity();
		if(!StringUtils.isBlank(dto.getHeadUrl())){
			user.setHeadUrl(dto.getHeadUrl());
		}
		if(!StringUtils.isBlank(dto.getUsername())){
			user.setUsername(dto.getUsername());
		}
		user.setUpdateDate(ZqDateUtil.getNow());
		if(!StringUtils.isBlank(dto.getReal_name())){
			user.setRealName(dto.getReal_name());
		}
		user.setId(ynuser.getId());
		baseDao.updateById(user);
		
		//认证信息
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username", ynuser.getMobile());
		List<YnDcLoginDTO> list = ynDcLoginService.list(params);
		//修改
		if(list != null && list.size() > 0){
			YnDcLoginDTO dc = list.get(0);
			YnDcLoginEntity entity = new YnDcLoginEntity();
			entity.setId(dc.getId());
			if(!StringUtils.isBlank(dto.getCardnoImage())){
				entity.setCardnoImage(dto.getCardnoImage());
			}
			if(!StringUtils.isBlank(dto.getNoticeMobile())){
				entity.setNoticeMobile(dto.getNoticeMobile());
			}
			if(!StringUtils.isBlank(dto.getJxName())){
				entity.setJxName(dto.getJxName());
			}
			if(!StringUtils.isBlank(dto.getJxMobile())){
				entity.setJxMobile(dto.getJxMobile());
			}
			if(!StringUtils.isBlank(dto.getJobqk())){
				entity.setJobqk(dto.getJobqk());
			}
			if(dto.getSex() != null){
				entity.setSex(dto.getSex());
			}
			if(dto.getMarriage() != null){
				entity.setMarriage(dto.getMarriage());
			}
			if(!StringUtils.isBlank(dto.getIncomeqk())){
				entity.setIncomeqk(dto.getIncomeqk());
			}
			entity.setUpdateDate(ZqDateUtil.getNow());
			ynDcLoginService.updateById(entity);
		//添加
		}else{
			YnDcLoginEntity entity = ConvertUtils.sourceToTarget(dto, YnDcLoginEntity.class);
			entity.setUsername(ynuser.getMobile());
			entity.setCreateDate(ZqDateUtil.getNow());
			ynDcLoginService.insert(entity);
		}
	}

	/**
	 * 查询用户信息
	 */
	@Override
	public YnUserDTO queryUserInfo(YnUserEntity ynuser) {
		YnUserDTO user = ConvertUtils.sourceToTarget(ynuser, YnUserDTO.class);
		user.setBalanceStr(MoneyUtil.bigDecimal2String(user.getBalance(), 0));
		if(user.getBalance().compareTo(BigDecimal.ZERO) <= 0){
			user.setBalance(BigDecimal.ZERO);
			user.setBalanceStr("0");
		}
		if(user.getReward().compareTo(BigDecimal.ZERO) <= 0){
			user.setReward(BigDecimal.ZERO);
		}
		//认证信息
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("username", ynuser.getMobile());
		List<YnDcLoginDTO> list = ynDcLoginService.list(params);
		if(list != null && list.size() > 0){
			YnDcLoginDTO dto = list.get(0);
			user.setDcInfo(dto);
		}
		return user;
	}

	/**
	 * 上传图片
	 */
	@Override
	@SuppressWarnings("rawtypes")
	public String uploadImage(HttpServletRequest request) {
        String url = "";
        try{
	        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
	        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
	                request.getSession().getServletContext());
	        //检查form中是否有enctype="multipart/form-data"
	        if(multipartResolver.isMultipart(request)){
	            //将request变成多部分request
	            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
	            //获取multiRequest 中所有的文件名
	            Iterator iter=multiRequest.getFileNames();
	            while(iter.hasNext()){
	                //一次遍历所有文件
	                MultipartFile file=multiRequest.getFile(iter.next().toString());
	                if(file!=null){
	                    // 获取文件名
	                    String fileName = file.getOriginalFilename();
	                    // 获取文件的后缀名
	                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
	
	        	        String fileNewName = String.valueOf(new StringBuilder(UUID.randomUUID().toString().replace("-", "")).append(suffixName));
	        	        
	        	        File newFile=new File(imgSavePath+"/"+fileNewName);
	        	        url = urlpath+fileNewName;
	                    //上传
	                    file.transferTo(newFile);
	                }
	            }
	        }
        }catch(Exception e){
        	log.error("上传图片异常：{}",e);
        }
        return url;
	}

	/**
	 * 条件查询用户列表
	 * @param sTime
	 * @param eTime
	 * @return
	 */
	@Override
	public PageInfo<YnUserEntity> queryByCondition(PageRequest dto, String sTime, String eTime) {
		Map<String,Object> pageParam = new HashMap<>();
		pageParam.put(Constant.PAGE,dto.getPageNo());
		pageParam.put(Constant.LIMIT, dto.getPageSize());
		IPage pageList =  baseDao.selectPage(
				getPage(pageParam,"create_date",false),
				new QueryWrapper<YnUserEntity>()
				.le(StrUtil.isNotEmpty(eTime), "create_date", eTime)
				.ge(StrUtil.isNotEmpty(sTime), "create_date", sTime)
		);
		PageInfo<YnUserEntity> pageInfo = new PageInfo<YnUserEntity>();
		pageInfo.setCount(pageList.getTotal());
		pageInfo.setList(pageList.getRecords());
		pageInfo.setPages(pageList.getPages());
		pageInfo.setPageNo(Long.parseLong(dto.getPageNo()));
		pageInfo.setPageSize(Long.parseLong(dto.getPageSize()));
		return pageInfo;
	}
	/**
	 * 每日数据
	 * @param s
	 * @param e
	 * @return
	 */
	@Override
	public String udata(String s, String e) {
        QueryWrapper<YnUserEntity> wrapper = new QueryWrapper<>();
		wrapper.ge("create_date", s);
		wrapper.le("create_date", e);
		List<YnUserEntity> order = baseDao.selectList(wrapper);
		int size = order.size();
		return size+"";
	}

}